package com.jiao.datasource.parse;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.jiao.comm.utils.LogUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;

/**
 * 抽象sql单元.
 * 记录一条sql 执行时候全部辅助信息.
 * @Author Vincent.jiao
 * @Date 2022/5/13 9:56
 */
public abstract class SQLUnitAbstract {
    @Getter
    private Connection connection;

    @Setter
    @Getter
    private boolean isBatch;    //是否批量

    @Getter
    private boolean isAutoCommit;   //是否自动提交

    @Getter
    private Statement statement;

    @Setter
    @Getter
    private String sql;     //执行sql

    @Getter
    private List<Object> params = new LinkedList<>();

    @Getter
    private List<List> batchParams = new LinkedList<>();

    public SQLUnitAbstract(Connection connection, Statement statement) {
        this.connection = connection;
        this.statement = statement;
        try {
            isAutoCommit = connection.getAutoCommit();
        } catch (SQLException e) {
            LogUtil.error(e.getMessage(), e);
        }
    }

    public void setParams (int index, Object val) {
        synchronized (params) {
            if (index >= this.params.size()) {
                this.params.add(val);
            } else {
                this.params.set(index, val);
            }
        }
    }

    /**
     * 主要针对 addBatch() 处理.
     */
    public void setBatchParams () {
        synchronized (params) {
            batchParams.add( JSONUtil.parseArray(params).toList(Object.class));    //深拷贝
            params.clear();
        }
    }

    public SQLUnitAbstract setBatch(boolean batch) {
        isBatch = batch;
        return this;
    }

    public SQLUnitAbstract setSql(String sql) {
        this.sql = sql;
        return this;
    }
}
